package com.qfedu.edu.aclservice.service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.edu.aclservice.feign.VipService;
import com.qfedu.edu.aclservice.mapper.UserMapper;
import com.qfedu.edu.aclservice.mapper.UserRoleMapper;
import com.qfedu.edu.bo.Account;
import com.qfedu.edu.bo.SecurityUser;
import com.qfedu.edu.po.Perm;
import com.qfedu.edu.po.Role;
import com.qfedu.edu.po.User;
import com.qfedu.edu.po.Vip;
import com.qfedu.edu.result.R;
import com.qfedu.edu.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author xiaobobo
 * @title: MyUserDetailService
 * @projectName seckill-fy-2401-parent
 * @description: TODO
 * @date 2024/11/4  16:42
 */
@Component
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private VipService vipService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //我们需要将这个json格式的字符串 转换成Java对象
        LoginVo loginVo = JSON.parseObject(s, LoginVo.class);
        //取出这个用户名和类型
        String username = loginVo.getUsername();
        Integer type = loginVo.getType();
        if (StringUtils.isEmpty(username)) {
            //说明用户名不对
            throw new UsernameNotFoundException("用户名不对");
        }
        if (type == 0) {
            //说明是管理员登陆
            return adminLogin(loginVo);
        } else {
            //说明是会员登陆
            return vipLogin(loginVo);
        }
    }

    /**
     * 会员登陆
     *
     * @param loginVo
     * @return
     */
    private UserDetails vipLogin(LoginVo loginVo) {
        R r = vipService.listUserByUsername(loginVo.getUsername());
        //接下来我们要获取数据
        LinkedHashMap vip = (LinkedHashMap) r.getDataMap().get("vip");
        //接下来我们就可以封装数据了
        Account account = new Account();
        account.setType(1);
        account.setUsername((String) vip.get("name"));
        account.setPassword((String) vip.get("password"));
        account.setId((String) vip.get("id"));

        SecurityUser securityUser = new SecurityUser();
        securityUser.setAccount(account);
        //然后设置权限和角色信息
        securityUser.setRoleAndPerms(new ArrayList<>());

        return securityUser;
    }

    /**
     * 管理员登陆
     *
     * @param loginVo
     * @return
     */
    private UserDetails adminLogin(LoginVo loginVo) {
        //先通过用户名查询用户对象
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", loginVo.getUsername());
        User user = userMapper.selectOne(userQueryWrapper);
        if (null == user) {
            throw new UsernameNotFoundException("用户名不对");
        }
        //执行到这里 说明用户名是对的
        //通过用户id查询权限信息
        List<Role> roles = listRoleByUserId(user.getUserId());
        List<Perm> perms = listPermByUserId(user.getUserId());
        //解下来将权限信息和角色信息封装成 List<String>
        List<String> roleAndPermList = wrapRoleAndPerm(roles, perms);
        //接下来封装对象
        SecurityUser securityUser = new SecurityUser();

        Account account = new Account();
        account.setType(0);
        account.setId(user.getUserId());
        account.setUsername(user.getUsername());
        account.setPassword(user.getPassword());
        securityUser.setAccount(account);

        securityUser.setRoleAndPerms(roleAndPermList);
        return securityUser;
    }

    /**
     * 封装权限和角色的数据
     *
     * @param roles
     * @param perms
     * @return
     */
    private List<String> wrapRoleAndPerm(List<Role> roles, List<Perm> perms) {
        List<String> stringList = new ArrayList<>();
        for (int i = 0; i < roles.size(); i++) {
            Role role = roles.get(i);
            stringList.add("ROLE_" + role.getRoleName());
        }
        for (int i = 0; i < perms.size(); i++) {
            Perm perm = perms.get(i);
            stringList.add(perm.getPermVal());
        }
        return stringList;
    }

    /**
     * 通过用户id查询权限
     *
     * @param userId
     * @return
     */
    private List<Perm> listPermByUserId(String userId) {
        List<Perm> perms = userRoleMapper.listPermByUserId(userId);
        return perms;
    }

    /**
     * 通过用户id查询角色
     *
     * @param userId
     * @return
     */
    private List<Role> listRoleByUserId(String userId) {
        List<Role> roles = userRoleMapper.listUserByUserId(userId);
        return roles;
    }
}
